<template>
  <div class="h-full flex flex-col">
    <div class="flex-1 flex flex-col min-h-0 overflow-hidden">
      <!-- 固定区域：标题、搜索、按钮组 -->
      <div class="flex-shrink-0">
        <!-- 顶部标题 -->
        <div class="flex justify-between items-center px-5 pt-4">
          <span class="text-xl font-bold text-gray-800">用户管理</span>
        </div>

        <!-- 搜索区域 - 使用 Ant Design Form -->
        <div class="px-5 pt-6">
          <a-form layout="inline" :model="searchQuery">
            <a-form-item label="用户名称">
              <a-input
                v-model:value="searchQuery.name"
                placeholder="请输入用户名称"
                allow-clear
                :style="{ width: '220px' }"
              />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="search">搜索</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>

        <!-- 按钮组 -->
        <div class="flex items-center gap-3 px-5 py-5">
          <!-- 新增按钮 -->
          <button
            class="px-5 py-1.5 bg-green-500 text-white rounded-lg shadow-sm hover:bg-green-600"
            @click="openModal"
          >
            新增管理员
          </button>

          <!-- 修改按钮 -->
          <button
            class="px-5 py-1.5 bg-blue-500 text-white rounded-lg shadow-sm hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed"
            @click="edit"
            :disabled="!selectedRows.length || selectedRows.length > 1"
          >
            修改
          </button>

          <!-- 批量删除按钮 -->
          <button
            class="px-4 py-1.5 bg-red-700 text-white rounded-lg shadow-sm hover:bg-red-600 disabled:bg-gray-400 disabled:cursor-not-allowed"
            @click="batchDelete"
            :disabled="!selectedRows.length"
          >
            批量删除
          </button>
        </div>
      </div>

      <!-- 可滚动的列表区域 -->
      <div class="flex-1 min-h-0 px-5 overflow-y-auto custom-scrollbar">
        <div v-if="loading" class="flex items-center justify-center h-full">
          <a-spin size="large">
            <template #indicator>
              <LoadingOutlined style="font-size: 24px" spin />
            </template>
          </a-spin>
        </div>
        <CommonTable
          v-else
          :columns="columns"
          :data="tags"
          :selectable="true"
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange"
        >
          <!-- 修改列模板，添加固定宽度和省略样式 -->
          <template #username="{ row }">
            <div class="fixed-width-cell" :title="row.username">
              {{ row.username }}
            </div>
          </template>
          <template #nickname="{ row }">
            <div class="fixed-width-cell" :title="row.nickname">
              {{ row.nickname }}
            </div>
          </template>
          <template #email="{ row }">
            <div class="fixed-width-cell" :title="row.email">
              {{ row.email }}
            </div>
          </template>
          <!-- 头像列 -->
          <template #avatar="{ row }">
            <a-avatar :src="row.avatar" :size="40" />
          </template>
          <!-- 性别列 -->
          <template #gender="{ row }">
            <span>{{ genderMap[row.gender] }}</span>
          </template>
          <!-- 角色列 -->
          <template #role="{ row }">
            <a-tag :color="roleMap[row.role].color">
              {{ roleMap[row.role].text }}
            </a-tag>
          </template>
          <!-- 状态列自定义渲染 -->
          <template #status="{ row }">
            <a-tag :color="statusMap[row.status].color">
              {{ statusMap[row.status].text }}
            </a-tag>
          </template>
          <!-- 操作列自定义渲染 -->
          <template #actions="{ row }">
            <div class="flex gap-2">
              <button
                class="text-blue-600 hover:text-blue-800"
                @click.stop="handleEdit(row)"
              >
                编辑
              </button>
              <button
                class="text-red-600 hover:text-red-800"
                @click.stop="handleDelete(row.id)"
              >
                删除
              </button>
            </div>
          </template>
        </CommonTable>
      </div>

      <!-- 固定在底部的分页 -->
      <div
        class="flex-shrink-0 flex justify-end items-center gap-4 px-2 py-2.5 bg-white border-t"
      >
        <span class="text-sm text-gray-600"> 共 {{ total }} 条 </span>
        <a-pagination
          v-model:current="currentPage"
          :total="total"
          :pageSize="pageSize"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
        />
      </div>
    </div>

    <!-- 使用新的模态框组件 -->
    <BaseModal
      v-model="showModal"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="680px"
      @confirm="handleSubmit"
      @close="closeModal"
    >
      <a-form :model="formData" :style="{ width: '100%' }">
        <div class="grid grid-cols-2 gap-x-4 gap-y-4">
          <a-form-item label="账号">
            <a-input
              v-model:value="formData.username"
              placeholder="请输入账号"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="昵称">
            <a-input
              v-model:value="formData.nickname"
              placeholder="请输入昵称"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <!-- 仅在新增时显示密码输入框 -->
          <a-form-item label="密码" v-if="!isEdit">
            <a-input-password
              v-model:value="formData.password"
              placeholder="请输入密码"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="头像">
            <a-input
              v-model:value="formData.avatar"
              placeholder="请输入头像URL"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="邮箱">
            <a-input
              v-model:value="formData.email"
              placeholder="请输入邮箱"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="职位">
            <a-input
              v-model:value="formData.position"
              placeholder="请输入职位"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="性别">
            <a-select
              v-model:value="formData.gender"
              :options="[
                { label: '男', value: 1 },
                { label: '女', value: 0 },
                { label: '保密', value: -1 }
              ]"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <!-- <a-form-item label="角色">
            <a-select
              v-model:value="formData.role"
              :options="[
                { label: '管理员', value: 0 },
                { label: '普通用户', value: 1 },
                { label: '会员', value: 2 }
              ]"
              :style="{ width: '220px' }"
            />
          </a-form-item> -->
          <a-form-item label="状态" class="col-span-2">
            <a-select
              v-model:value="formData.status"
              :options="[
                { label: '正常', value: '1' },
                { label: '禁用', value: '0' }
              ]"
              :style="{ width: '220px' }"
            />
          </a-form-item>
          <a-form-item label="个性签名" class="col-span-2">
            <a-textarea
              v-model:value="formData.sign"
              placeholder="请输入个性签名"
              :rows="3"
              :style="{ width: '100%' }"
            />
          </a-form-item>
        </div>
      </a-form>
    </BaseModal>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { userApi } from "@/api/backend/userManagement.js";
import CommonTable from "@/components/common/CommonTable.vue";
import {
  Pagination as APagination,
  Input as AInput,
  Select as ASelect,
  Form as AForm,
  FormItem as AFormItem,
  Space as ASpace,
  Button as AButton,
  message,
  Modal as AModal,
  Avatar as AAvatar,
  Tag as ATag,
  Spin as ASpin,
} from "ant-design-vue";
import { LoadingOutlined } from "@ant-design/icons-vue";
import BaseModal from "@/components/common/BaseModal.vue";

// 修改列定义
const columns = [
  { key: "nickName", title: "昵称", width: "160px" },
  { key: "avatar", title: "头像", width: "100px" },
  { key: "gender", title: "性别", width: "100px" },
  { key: "position", title: "职位", width: "160px" },
  { key: "role", title: "角色", width: "120px" },
  { key: "status", title: "状态", width: "120px" },
  { key: "actions", title: "操作", width: "120px" },
];

// 添加状态映射
const statusMap = {
  1: { text: "正常", color: "success" },
  0: { text: "封禁", color: "error" },
  [-1]: { text: "删除", color: "default" },
};

// 添加角色映射
const roleMap = {
  0: { text: "管理员", color: "blue" },
  1: { text: "用户", color: "green" },
  2: { text: "会员", color: "gold" },
};

// 添加性别映射
const genderMap = {
  1: "男",
  0: "女",
  [-1]: "保密",
};

// 行点击处理
const handleRowClick = (row) => {
  console.log("行点击:", row);
};

// 修改搜索状态对象
const searchQuery = ref({
  name: "",
  status: undefined,
});

// 状态
const tags = ref([]);
const currentPage = ref(1);
const totalPages = ref(1);
const total = ref(0);
const showModal = ref(false);
const isEdit = ref(false);

// 修改formData的默认状态
const getDefaultFormData = () => ({
  username: "",
  nickname: "",
  email: "",
  status: "1",
  password: "",
  avatar: "",
  sign: "",
  gender: -1,
  position: "",
  role: 1,
});

const formData = ref(getDefaultFormData());
const pageSize = ref(7);

// 修改状态选项数据
const statusOptions = [
  { label: "启用", value: "1" },
  { label: "停用", value: "0" },
];

// 添加加载状态
const loading = ref(true);

// 方法定义
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

const handlePageChange = (page) => {
  currentPage.value = page;
  loadData();
};

const handleSizeChange = (current, size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadData();
};

const openModal = () => {
  isEdit.value = false;
  formData.value = getDefaultFormData();
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  formData.value = getDefaultFormData();
};

// 修改handleEdit方法
const handleEdit = (row) => {
  isEdit.value = true;
  formData.value = {
    id: row.id || '',
    username: row.username || '',
    nickname: row.nickname || '',
    email: row.email || '',
    status: row.status === undefined ? '1' : String(row.status),
    avatar: row.avatar || '',
    sign: row.sign || '',
    gender: row.gender === undefined ? -1 : row.gender,
    position: row.position || '',
    role: row.role === undefined ? 1 : row.role
  };
  showModal.value = true;
};

// 修改edit方法
const edit = async () => {
  if (selectedRows.value.length === 0) {
    message.warning("请选择要修改的数据");
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning("只能选择一条数据进行修改");
    return;
  }

  const selectedRow = selectedRows.value[0];
  isEdit.value = true;
  formData.value = {
    id: selectedRow.id || '',
    username: selectedRow.username || '',
    nickname: selectedRow.nickname || '',
    email: selectedRow.email || '',
    status: selectedRow.status === undefined ? '1' : String(selectedRow.status),
    avatar: selectedRow.avatar || '',
    sign: selectedRow.sign || '',
    gender: selectedRow.gender === undefined ? -1 : selectedRow.gender,
    position: selectedRow.position || '',
    role: selectedRow.role === undefined ? 1 : selectedRow.role
  };
  showModal.value = true;
};

// 修改单个删除方法
const handleDelete = async (id) => {
  AModal.confirm({
    title: "确认删除",
    content: "确定要删除这条数据吗？",
    okText: "确定",
    cancelText: "取消",
    async onOk() {
      try {
        await userApi.delete(id);
        message.success("删除成功");
        await loadData();
      } catch (error) {
        console.error("删除失败:", error);
        message.error("删除失败");
      }
    },
  });
};

const handleSubmit = async () => {
  try {
    if (!formData.value.username) {
      message.warning("请输入账号");
      return;
    }
    if (!isEdit.value && !formData.value.password) {
      message.warning("请输入密码");
      return;
    }
    if (!formData.value.email) {
      message.warning("请输入邮箱");
      return;
    }

    const submitData = {
      username: formData.value.username,
      nickname: formData.value.nickname,
      email: formData.value.email,
      status: parseInt(formData.value.status),
      avatar: formData.value.avatar,
      sign: formData.value.sign,
      gender: formData.value.gender,
      position: formData.value.position,
      role: formData.value.role
    };

    // 只在新增时提交密码
    if (!isEdit.value) {
      submitData.password = formData.value.password;
    }

    if (isEdit.value) {
      submitData.id = formData.value.id;
      await userApi.update(submitData);
      message.success("修改成功");
    } else {
      await userApi.create(submitData);
      message.success("新增成功");
    }

    showModal.value = false;
    await loadData();
  } catch (error) {
    console.error("操作失败:", error);
    message.error(error.message || "操作失败");
  }
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      username: searchQuery.value.name || undefined,
      status: searchQuery.value.status || undefined,
    };

    const response = await userApi.getList(params);
    tags.value = response.data.data;
    total.value = parseInt(response.data.total);
    currentPage.value = parseInt(response.data.pageNumber);
    pageSize.value = parseInt(response.data.pageSize);
    totalPages.value = parseInt(response.data.totalPages);
  } catch (error) {
    console.error("加载失败:", error);
  } finally {
    loading.value = false;
  }
};

// 添加选择变化处理函数
const handleSelectionChange = (selected) => {
  console.log("选择变化，选中的数据:", selected);
  selectedRows.value = selected;
};

// 添加选中行数据存储
const selectedRows = ref([]);

// 搜索方法
const search = () => {
  currentPage.value = 1;
  loadData();
};

// 重置方法修改
const reset = () => {
  searchQuery.value = {
    name: "",
    status: undefined,
  };
  currentPage.value = 1;
  loadData();
};

// 修改批量删除方法
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning("请选择要删除的数据");
    return;
  }

  console.log("selectedRows.value:", selectedRows.value);

  AModal.confirm({
    title: "确认删除",
    content: `确定要删除这 ${selectedRows.value.length} 条数据吗？`,
    okText: "确定",
    cancelText: "取消",
    async onOk() {
      try {
        const ids = Array.from(selectedRows.value).map((id) => parseInt(id));
        console.log("收集到的ids:", ids);

        if (ids.length === 0) {
          message.error("未能获取到有效的ID");
          return;
        }

        await userApi.batchDelete(ids);
        message.success("批量删除成功");
        await loadData();
        selectedRows.value = [];
      } catch (error) {
        console.error("批量删除失败:", error);
        message.error("批量删除失败");
      }
    },
  });
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
/* 自定义滚动条样式 */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 6px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #d4d4d4;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* 火狐浏览器滚动条样式 */
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #d4d4d4 #f1f1f1;
  height: 100%;
  padding: 1px; /* 防止边界问题 */
}
@keyframes zoomIn {
  from {
    opacity: 0;
    transform: scale(0.3);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 关闭动画 */
:deep(.tag-modal.ant-modal-wrap-rtl .ant-modal) {
  animation: zoomOut 0.2s ease-in !important;
}

@keyframes zoomOut {
  from {
    opacity: 1;
    transform: scale(1);
  }
  to {
    opacity: 0;
    transform: scale(0.3);
  }
}

/* 调整表单用户样式 */
:deep(.ant-form-item-label > label) {
  font-weight: 500; /* 设置用户文字加粗 */
}

/* 保持用户加粗 */
:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  height: 32px;
  margin-bottom: 0;
}

.fixed-width-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
}

:deep(.ant-table-thead > tr > th) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 添加加载动画样式 */
.ant-spin {
  color: #1890ff;
}
</style>
